package com.mybatis.jpa.SqlProvider;

import com.mybatis.jpa.meta.MetaCell;
import org.apache.ibatis.builder.annotation.ProviderContext;
import org.apache.ibatis.jdbc.SQL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @Author lgt
 * @Date 2017/10/9 : 17:43
 */
public class InsertSqlProvider {

    private static final Logger logger = LoggerFactory.getLogger(InsertSqlProvider.class);

    public String insert(Object t, ProviderContext context) throws NoSuchFieldException, IllegalAccessException {
        Check.notNull(t, "insert must not be null");
        MetaCell meta = ProviderUtil.getMetaCellByMapper(context);
        SQL sql = new SQL();
        sql.INSERT_INTO(meta.getTableName());
        String[] fields = meta.getFields();
        String[] columns = meta.getColumns();
        for (int i = 0; i < fields.length; i++) {
            sql.VALUES(columns[i], "#{" + fields[i] + "}");
        }
        System.out.println(sql.toString());
        logger.debug("insert sql :{}", sql.toString());
        return sql.toString();
    }


    @SuppressWarnings("unchecked")
    public String insertBatch(Map map, ProviderContext context) {
        MetaCell meta = ProviderUtil.getMetaCellByMapper(context);
        List<Object> list = (List<Object>) map.get("list");
        Check.notNull(list, "list must not be null");
        StringBuilder sql = new StringBuilder();
        sql.append("INSERT INTO ");
        sql.append(meta.getTableName());
        sql.append("( ");
        for (int i = 0; i < meta.getFields().length; i++) {
            sql.append(meta.getColumns()[i]);
            if (i < meta.getFields().length - 1) {
                sql.append(",");
            }
        }
        sql.append(") VALUES ");
        for (int i = 0; i < list.size(); i++) {
            sql.append(" ( ");
            for (int j=0 ;j<meta.getFields().length;j++) {
                sql.append("#{list[").append(i).append("].");
                sql.append(meta.getFields()[j]);
                sql.append("}");
                if (j < meta.getFields().length - 1) {
                    sql.append(",");
                }
            }
            sql.append(" ) ");
            if (i < list.size() - 1) {
                sql.append(",");
            }
        }
        logger.debug("insertBatch sql :{}", sql.toString());
        return sql.toString();
    }
}
